import datetime
now = datetime.datetime.now()
print ("Última versión:")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
import pandas as pd
import numpy as np
import pandas_profiling
from itertools import combinations
from dateutil.parser import parse
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import seaborn as sns
import plotly.express as px
#se carga el dataframe con los resultados de 8 indicadores (todos los PCA considerados en k-medias):
resultados_ind8 = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/3_Agrupamiento-Kmeans/Resultados_Mun_Indic_PCA_Kmeans_Atip_ind8.csv", dtype={'EDO':int,'MUN':int})
#se carga el dataframe con los resultados de 8 indicadores, con log en LNE y Densidad_LNE (todos los PCA considerados en k-medias):
resultados_ind8_tf = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/3_Agrupamiento-Kmeans/Resultados_Mun_Indic_PCA_Kmeans_Atip_ind8_tf.csv", dtype={'EDO':int,'MUN':int})
#se aplica np.exp rn LNE y Densidad_LNE para volver a las magnitudes originales
resultados_ind8_tf['log(LNE)'] = np.exp(resultados_ind8_tf['log(LNE)'])
resultados_ind8_tf['log(Densidad_LNE)'] = np.exp(resultados_ind8_tf['log(Densidad_LNE)'])
#renombramos algunas columnas
resultados_ind8_tf=resultados_ind8_tf.rename(columns={"log(LNE)": "LNE", "log(Densidad_LNE)": "Densidad_LNE"})
resultados_ind8_tf
#con pandas_profiling se crea una interface para visualizar un resumen del dataframe de los resultados
resultados_ind8.profile_report()
#se ordenan y obtienen los 10 municipios por nivel de complejidad (descendente en CP1)
ranking_mun_top10_ind8 = resultados_ind8.sort_values(by='CP1_(ICE_principal)', ascending=False).head(10)
#se guarda el ranking
ranking_mun_top10_ind8.to_csv(r'Resultados_Mun_ranking-top10_ind8.csv', index = None)
ranking_mun_top10_ind8
#se obtienen los municipios de mayor complejidad (mayor CP1) para cada una de las 32 entidades
idx_rank_mun = resultados_ind8.groupby(['EDO'])['CP1_(ICE_principal)'].transform(max) == resultados_ind8['CP1_(ICE_principal)']
ranking_mun_edo = resultados_ind8[idx_rank_mun]
ranking_mun_edo.to_csv(r'Resultados_Mun_ranking-edo_ind8.csv', index = None)
ranking_mun_edo
Animación de la proyección de los municipios en el espacio de las CP (tipología en color):
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
#3-d scatter plot con plotly
fig = px.scatter_3d(resultados_ind8,
x='CP1_(ICE_principal)',
y='CP2_(segundo_ICE)',
z='CP3_(tercer_ICE)',
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey'},
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti)
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
title="Proyección de los municipios en el espacio de las Componentes Principales (8 indicadores)",
legend_orientation="h")
fig.show()
#salvar animación en html
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Proyeccion3d_Mun_ind8.html")
Animación de la proyección de los municipios en el espacio de las CP (atipicidad en color):
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
#3-d scatter plot con plotly
fig = px.scatter_3d(resultados_ind8,
x='CP1_(ICE_principal)',
y='CP2_(segundo_ICE)',
z='CP3_(tercer_ICE)',
color='Atipicidad',
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti)
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
title="Proyección de los municipios en el espacio de las Componentes Principales (8 indicadores)",
legend_orientation="h")
fig.show()
#salvar animación en html
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Proyeccion3d_Mun_Atip_ind8.html")
#con pandas_profiling se crea una interface para visualizar un resumen del dataframe de los resultados
resultados_ind8_tf.profile_report()
#se ordenan y obtienen los 10 municipios por nivel de complejidad (descendente en CP1)
ranking_mun_top10_ind8_tf = resultados_ind8_tf.sort_values(by='CP1_(ICE_principal)', ascending=False).head(10)
#se guarda el ranking
ranking_mun_top10_ind8_tf.to_csv(r'Resultados_Mun_ranking-top10_ind8_tf.csv', index = None)
ranking_mun_top10_ind8_tf
#se obtienen los municipios de mayor complejidad (mayor CP1) para cada una de las 32 entidades
idx_rank_mun = resultados_ind8_tf.groupby(['EDO'])['CP1_(ICE_principal)'].transform(max) == resultados_ind8_tf['CP1_(ICE_principal)']
ranking_mun_edo_tf = resultados_ind8_tf[idx_rank_mun]
ranking_mun_edo_tf.to_csv(r'Resultados_Mun_ranking-edo_ind8_tf.csv', index = None)
ranking_mun_edo_tf
Animación de la proyección de los municipios en el espacio de las CP (tipología en color):
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
#3-d scatter plot con plotly
fig = px.scatter_3d(resultados_ind8_tf,
x='CP1_(ICE_principal)',
y='CP2_(segundo_ICE)',
z='CP3_(tercer_ICE)',
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey'},
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti)
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
title="Proyección de los municipios en el espacio de las Componentes Principales (8 indicadores con transformación log)",
legend_orientation="h")
fig.show()
#salvar animación en html
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Proyeccion3d_Mun_ind8_tf.html")
Animación de la proyección de los municipios en el espacio de las CP (atipicidad en color):
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
#3-d scatter plot con plotly
fig = px.scatter_3d(resultados_ind8_tf,
x='CP1_(ICE_principal)',
y='CP2_(segundo_ICE)',
z='CP3_(tercer_ICE)',
color='Atipicidad',
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti)
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
title="Proyección de los municipios en el espacio de las Componentes Principales (8 indicadores con transformación log)",
legend_orientation="h")
fig.show()
#salvar animación en html
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Proyeccion3d_Mun_Atip_ind8_tf.html")
import geopandas as gpd
#se carga la cartografía se municipios (shapefile)
fp = "C:/Users/miguel.alvarez/Google Drive/Cartografias/Cartografia INE/municipio.shp"
mapa_mun = gpd.read_file(fp)
#type(mapa_mun)
#mapa_mun
#se cambia la columna id con la concatenación de entidad+municipio
mapa_mun["id"] = mapa_mun["entidad"].astype(str) + mapa_mun["municipio"].astype(str)
mapa_mun
#muestra de la cartografía de municipios
plt.rcParams['figure.figsize'] = [50, 70]
mapa_mun.plot(edgecolor='black')
#se guarda shapefile en geojson
mapa_mun.to_file("municipios.geojson", driver='GeoJSON')
#se carga la cartografía de estados (shapefile)
fp2 = "C:/Users/miguel.alvarez/Google Drive/Cartografias/Cartografia INE/entidad.shp"
mapa_edo = gpd.read_file(fp2)
#type(mapa_edo)
mapa_edo["id"] = mapa_edo["entidad"].astype(str)
mapa_edo.head()
#muestra de la cartografía de estados
plt.rcParams['figure.figsize'] = [50, 70]
mapa_edo.plot(edgecolor='black')
#se agrega una column id a resultados_ind8
resultados_ind8["id"] = resultados_ind8["EDO"].astype(str) + resultados_ind8["MUN"].astype(str)
#se une con mapa_mun
mapa_mun_ind8 = mapa_mun.merge(resultados_ind8, how='inner',on=['id'])
mapa_mun_ind8.head()
#mapa tipología
base = mapa_edo.plot(facecolor="none", edgecolor='black')
mapa_mun_ind8.plot(ax=base,
column='TCE_municipal',
categorical=True,
edgecolor='white',
legend=True)
#mapa municipios atípicos
base = mapa_edo.plot(facecolor="none", edgecolor='black')
mapa_mun_ind8.plot(ax=base,
column='Atipicidad',
categorical=True,
edgecolor='white',
legend=True)
import json
with open('C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/municipios.geojson') as f:
municipios_s = json.load(f)
#print(municipios_s["features"][0])
#print(municipios_s["features"][0]["properties"])
#municipios_s
import plotly
#mapa de TCE
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
fig = px.choropleth(resultados_ind8, geojson=municipios_s,
locations='id', featureidkey="properties.id",
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey'},
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti,
title = 'TCE municipal (8 indicadores)')
fig.update_geos(fitbounds="locations",
visible=False,
showcountries=True,
countrycolor="Black", showsubunits=True,
subunitcolor="Blue")
fig.show()
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Mapa_Mun_ind8.html")
import plotly
#mapa de atipicidad
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
fig = px.choropleth(resultados_ind8, geojson=municipios_s,
locations='id', featureidkey="properties.id",
color='Atipicidad',
color_discrete_sequence= px.colors.sequential.Reds,
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti,
title = 'Mapa municipios atípicos (8 indicadores)')
fig.update_geos(fitbounds="locations",
visible=True,
showcountries=True,
countrycolor="Black",
showsubunits=True,
subunitcolor="Blue")
fig.show()
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Mapa_Mun_Atip_ind8.html")
#se agrega una column id a resultados_ind8
resultados_ind8_tf["id"] = resultados_ind8_tf["EDO"].astype(str) + resultados_ind8_tf["MUN"].astype(str)
#se une con mapa_mun
mapa_mun_ind8_tf = mapa_mun.merge(resultados_ind8_tf, how='inner',on=['id'])
mapa_mun_ind8_tf.head()
#mapa tipología
base = mapa_edo.plot(facecolor="none", edgecolor='black')
mapa_mun_ind8_tf.plot(ax=base,
column='TCE_municipal',
categorical=True,
edgecolor='white',
legend=True)
#mapa municipios atípicos
base = mapa_edo.plot(facecolor="none", edgecolor='black')
mapa_mun_ind8_tf.plot(ax=base,
column='Atipicidad',
categorical=True,
edgecolor='white',
legend=True)
import plotly
#mapa de TCE
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
fig = px.choropleth(resultados_ind8_tf, geojson=municipios_s,
locations='id', featureidkey="properties.id",
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey'},
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti,
title = 'TCE municipal (8 indicadores con transformación log)')
fig.update_geos(fitbounds="locations",
visible=False,
showcountries=True,
countrycolor="Black", showsubunits=True,
subunitcolor="Blue")
fig.show()
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Mapa_Mun_ind8_tf.html")
import plotly
#mapa de atipicidad
eti=['NOMBRE_ESTADO','NUM_SECC_RUR', 'LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'CP1_(ICE_principal)', 'CP2_(segundo_ICE)', 'CP3_(tercer_ICE)', 'TCE_municipal', 'Atipicidad']
fig = px.choropleth(resultados_ind8_tf, geojson=municipios_s,
locations='id', featureidkey="properties.id",
color='Atipicidad',
color_discrete_sequence= px.colors.sequential.Reds,
hover_name='NOMBRE_MUNICIPIO',
hover_data = eti,
title = 'Mapa municipios atípicos (8 indicadores con transformación log)')
fig.update_geos(fitbounds="locations",
visible=False,
showcountries=True,
countrycolor="Black",
showsubunits=True,
subunitcolor="Blue")
fig.show()
fig.write_html("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/4_Resumen-Mapas/Pyplotly_Mapa_Mun_Atip_ind8_tf.html")